/**
 * @module initWebSocket 初始化
 * @module websocketonopen 连接成功
 * @module websocketonerror 连接失败
 * @module websocketclose 断开连接
 * @module resetHeart 重置心跳
 * @module sendSocketHeart 心跳发送
 * @module reconnect 重连
 * @module sendMsg 发送数据
 * @module websocketonmessage 接收数据
 * @module test 测试收到消息传递
 * @description socket 通信
 * @param {any} url socket地址
 * @param {any} websocket websocket 实例
 * @param {any} heartTime 心跳定时器实例
 * @param {number} socketHeart 心跳次数
 * @param {number} HeartTimeOut 心跳超时时间
 * @param {number} socketError 错误次数
 */

import { getToken } from '@/utils/auth';
import { ElNotification } from 'element-plus';
import useNoticeStore from '@/store/modules/notice';
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading';
import {closeDownload} from "@/api/commission/commissionList/index";
import type { Action } from 'element-plus'

let socketUrl: any = ''; // socket地址
let websocket: any = null; // websocket 实例
let heartTime: any = null; // 心跳定时器实例
let socketHeart = 0 as number; // 心跳次数
const HeartTimeOut = 10000; // 心跳超时时间 10000 = 10s
let socketError = 0 as number; // 错误次数

// 初始化socket
export const initWebSocket = (url: any) => {
  if (import.meta.env.VITE_APP_WEBSOCKET === 'false') {
    return;
  }
  socketUrl = url;
  // 初始化 websocket
  websocket = new WebSocket(url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID);
  websocketonopen();
  websocketonmessage();
  websocketonerror();
  websocketclose();
  sendSocketHeart();
  return websocket;
};

// socket 连接成功
export const websocketonopen = () => {
  websocket.onopen = function () {
    console.log('连接 websocket 成功');
    resetHeart();
  };
};

// socket 连接失败
export const websocketonerror = () => {
  websocket.onerror = function (e: any) {
    console.log('连接 websocket 失败', e);
  };
};

// socket 断开链接
export const websocketclose = () => {
  websocket.onclose = function (e: any) {
    console.log('断开连接', e);
  };
};

// socket 重置心跳
export const resetHeart = () => {
  socketHeart = 0;
  socketError = 0;
  clearInterval(heartTime);
  sendSocketHeart();
};

// socket心跳发送
export const sendSocketHeart = () => {
  heartTime = setInterval(() => {
    // 如果连接正常则发送心跳
    if (websocket.readyState == 1) {
      // if (socketHeart <= 30) {
      websocket.send(
        JSON.stringify({
          type: 'ping'
        })
      );
      socketHeart = socketHeart + 1;
    } else {
      // 重连
      reconnect();
    }
  }, HeartTimeOut);
};

// socket重连
export const reconnect = () => {
  if (socketError <= 2) {
    clearInterval(heartTime);
    initWebSocket(socketUrl);
    socketError = socketError + 1;
    // eslint-disable-next-line prettier/prettier
    console.log('socket重连', socketError);
  } else {
    // eslint-disable-next-line prettier/prettier
    console.log('重试次数已用完');
    clearInterval(heartTime);
  }
};

// socket 发送数据
export const sendMsg = (data: any) => {
  websocket.send(data);
};

// socket 接收数据
export const websocketonmessage = () => {
  var notificationHandle = null;//用来控制长连接的进度条
  websocket.onmessage = function (e: any) {
    if (e.data.indexOf('heartbeat') > 0) {
      resetHeart();
    }
    if (e.data.indexOf('ping') > 0) {
      return;
    }

      //接收下载链接
    if(e.data.indexOf('exportUrl') > -1){
      let url = e.data.split('$')[1];
      let flag = e.data.split('$')[2]
      exportFile(url,flag);
      return e.data;
    }
  
      //接收刷新后还没下载的标志
    if(e.data.indexOf('loading') > -1){
      loading = e.data.split('$')[1]
      formName = e.data.split('$')[2]
      localStorage.setItem('formName',formName)
      localStorage.setItem('loading',loading)
      return e.data;
    }

    //添加建立长连接的webscoket进度条
    if (e.data.indexOf('longConnection') > -1) {
      // 使用正则表达式匹配 ${} 中的内容
      let content = e.data.match(/\$content{(.*?)\}/)[1];
      let title = e.data.match(/\$title{(.*?)\}/)[1];
      let type = e.data.match(/\$type{(.*?)\}/)[1];

      if(notificationHandle == null){
        notificationHandle = addLongMessage(title,content,type);
        console.log(notificationHandle)
      }
      else{
        // 更新现有通知的内容
        notificationHandle.close();
        notificationHandle = addLongMessage(title,content,type);

      }
      return e.data;
    }
    else if (e.data.indexOf('shutDownLongConnection') > -1) {
      // 使用正则表达式匹配 ${} 中的内容
      let content = e.data.match(/\$content{(.*?)\}/)[1];
      let title = e.data.match(/\$title{(.*?)\}/)[1];
      let type = e.data.match(/\$type{(.*?)\}/)[1];

      notificationHandle.close();
      notificationHandle = closeLongMessage(title,content,type);
      return e.data;
    }
    useNoticeStore().addNotice({
      message: e.data,
      read: false,
      time: new Date().toLocaleString()
    });
    ElNotification({
      title: '消息',
      message: e.data,
      type: 'success',
      duration: 3000
    });
    return e.data;
  };

};


//导出的url下载链接
export let downloadUrl:string
let downloadLoadingInstance: LoadingInstance;
//刷新标志
let loading:string
//表单的名字
let formName:string
document.addEventListener('DOMContentLoaded', function() {
  if (performance.navigation.type === 1) {
    let flag = localStorage.getItem('loading')
    //如果flag代表是0则还没下载，则告诉用户后台正在下载中
    if(flag==='0'){
      open2()
    }
  }
});

//下载成功,提示时间5秒
const open1 = () => {
  ElMessageBox.alert(localStorage.getItem('formName') + '成功下载', {
    confirmButtonText: '确认',
    callback: (action: Action) => {
       ElNotification({
       title: '温馨提示',
       message:   localStorage.getItem('formName') + '成功下载',
       type: 'success',
       duration: 2000
  })
    },
  })
}
//提示后台正在下载中
const open2 = () => {
  ElNotification({
    title: '温馨提示',
    message: localStorage.getItem('formName') + '正在下载中，请耐心等待',
    type: 'warning',
    duration: 10000
  })
}
//浏览器下载文件的操作
const exportFile = (urlFile,flag) => {
  //如果是刷新了浏览器下载还没有完成，那么继续加载下载界面
  if(flag>0){
    downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' });
  }
  //判断是否已经下载过,等于1代表没有下载
  if (flag==="1"){
    //发送请求关闭
    closeDownload();
    //线程休眠0.5秒,确保已经取消操作
    setTimeout(() => {        
      },500)
    downloadLoadingInstance.close();
    //网页自动下载操作
    localStorage.setItem('hasDownloaded', 'false');
    const link = document.createElement('a');
    link.href = urlFile;
    link.setAttribute('download', `commissionList_${new Date().getTime()}.xlsx`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    setTimeout(() => {//1.5秒后提示成功下载
      open1()
      localStorage.setItem('loading','1') //去掉刷新不可下载的标志设置为可下载
    },1500)
  }
};


//添加长连接的弹窗
export const addLongMessage = (title,content,type) => {
  if(type=='message'){
    return   ElMessage({
      message:
        '  <div style="width: auto;text-align: center;">\n' +
        '    <h3 style="">'+title+'</h3>\n' +
        '    <div style="width: 300px; height: 25px; background-color: #b2b2b2; border-radius: 10px; overflow: hidden; position: relative;">\n' +
        '      <div style="width: '+content+'%; height: 100%; background-color: #4caf50; text-align: center; line-height: 25px; color: white; position: absolute; left: 0; top: 0;"></div>\n' +
        '      <div style="position: absolute; right: 0; top: 0; height: 100%; line-height: 25px; color: white; padding-right: 10px;">\n' +
        content+'%' +
        '      </div>' +
        '    </div>' +
        '  </div>',
      dangerouslyUseHTMLString: true,
      showClose: false,
      showConfirmButton: false,
      customClass: 'no-animation',
      duration: 0,
      offset: 400,
      type: 'warning',
      center: true,
      icon: ''
    })
  }else if (type == 'notification'){
    return ElNotification({
      title: title,
      dangerouslyUseHTMLString: true,
      message:
        '    <div style="width: 250px; height: 25px; background-color: #b2b2b2; border-radius: 10px; overflow: hidden; position: relative; ">\n' +
        '      <div style="width: '+content+'%; height: 100%; background-color: #4caf50; text-align: center; line-height: 25px; color: white; position: absolute; left: 0; top: 0;"></div>\n' +
        '      <div style="position: absolute; right: 0; top: 0; height: 100%; line-height: 25px; color: white; padding-right: 10px;">\n' +
        content+'%' +
        '      </div>' +
        '    </div>',
      duration: 0,
      offset: 100,
      type: '',
      customClass: 'no-animation' // 需要添加一个自定义类来禁用动画
    });
  } else {
    return null;
  }
};

//断开长连接的弹窗
export const closeLongMessage = (title,content,type) => {
  if(type=='message'){
    return   ElMessage({
      message:
        '  <div style="width: auto; ">\n' +
        '    <h3 style="margin-right: 10px;">'+title+'</h3>\n' +
        '    <div style="width: 300px; height: 25px; background-color: #b2b2b2; border-radius: 10px; overflow: hidden; position: relative;">\n' +
        '      <div style="width: '+content+'%; height: 100%; background-color: #4caf50; text-align: center; line-height: 25px; color: white; position: absolute; left: 0; top: 0;"></div>\n' +
        '      <div style="position: absolute; right: 0; top: 0; height: 100%; line-height: 25px; color: white; padding-right: 10px;">\n' +
        content+'%' +
        '      </div>' +
        '    </div>' +
        '  </div>',
      dangerouslyUseHTMLString: true,
      showClose: false,
      showConfirmButton: false,
      customClass: 'no-animation',
      duration: 2000,
      offset: 400,
      type: 'success',
    })
  }else if (type == 'notification'){
    return  ElNotification({
      title: title,
      dangerouslyUseHTMLString: true,
      // message: '<div style=" width: 100px; height: 25px; background-color: #b2b2b2; border-radius: 10px; margin: 20px; overflow: hidden;">' +
      //   '  <div style="width: '+content+'%; height: 100%; background-color: #4caf50; text-align: center; line-height: 25px; color: white;">' +
      //   content+'%' +
      //   '  </div>' +
      //   '</div>',
      duration: 3000,
      offset: 100,
      type: "success",
      customClass: 'no-animation' // 需要添加一个自定义类来禁用动画
    });
  } else {
    return null;
  }
};
